package com.v1.video.activity;

import java.util.ArrayList;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AlphabetIndexer;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SectionIndexer;
import android.widget.TextView;

import com.iss.view.common.ToastAlone;
import com.iss.view.pulltorefresh.PullToRefreshListView;
import com.v1.video.R;
import com.v1.video.adapter.FriendsListAdapter;
import com.v1.video.domain.GetFriendBySharePageInfo;
import com.v1.video.domain.GetUserFriendPageInfo;
import com.v1.video.domain.PlayerInfo;
import com.v1.video.engine.NetEngine;
import com.v1.video.util.Helper;
import com.v1.video.util.Logger;
import com.v1.video.util.Utils;

/***
 * 选择好友的activity：类似联系人的布局；以字母分组；
 * @author fengtao
 * 进本类需传参数：userId，
 * groudId（圈子id）针对拉好友进圈子用
 */
public class MyFriendsActivity extends BaseActivity{
	private final String TAG = "MyFriendsActivity";
	/** 本页面的头— title条 */
    LinearLayout layout_head = null;
    /** 标题与按钮的父背景 */
    RelativeLayout layout_head_title = null;
    /** 标题 */
    TextView text_title;
    TextView btn_title_left;    
    
    private PullToRefreshListView refreshListViewFriends;
	private ListView listView;
	private FriendsListAdapter adapter;
	private String userId;
	private String groupId;
	
	/*shenjin add*/
	private ArrayList<PlayerInfo> mSelectedFriends;//已经选择的圈成员，可能是从上级页面传入
	
	/**
	 * 定义字母表的排序规则
	 */
	private String alphabet = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	/**
	 * 用于进行字母表分组
	 */
	private AlphabetIndexer indexer;
	/**
	 * 分组的布局
	 */
	private RelativeLayout titleLayout;
	/**
	 * 分组上显示的字母
	 */
	private TextView title;
	
	/**
	 * 右侧可滑动字母表
	 */
	private Button alphabetButton;
	/**
	 * 弹出式分组的布局
	 */
	private RelativeLayout sectionToastLayout;
	/**
	 * 弹出式分组上的文字
	 */
	private TextView sectionToastText;
	
	/**
	 * 是否可以多选 false:不可以，true:可以，默认是可以的
	 */
	private boolean isCanDouble = true;
	public final String strCanDouble = "isCanDouble";
	/**
	 * 入口：表示从哪个类进入，可以用以区别不同的功能；
	 * 0:从圈子有关的进，比如创建圈子，或圈子设置
	 * 1：从发布视频的口进，提醒好友用的
	 */
	private int flag = 0;
	
	private Button btnSure = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_myfriends);
	}

	@Override
	protected void initView() {
		// TODO Auto-generated method stub	
		
		layout_head = (LinearLayout) findViewById(R.id.myfriends_title_back);
        layout_head_title = (RelativeLayout) findViewById(R.id.head_top_myfriends);
        layout_head_title.setVisibility(View.VISIBLE);
        btn_title_left = (TextView) findViewById(R.id.head_myfriends_left1);        
        
        listView = (ListView)findViewById(R.id.myfriends_listview);
//        refreshListViewFriends = (PullToRefreshListView)findViewById(R.id.myfriends_listview);
//        refreshListViewFriends.setMode(Mode.DISABLED);
//        listView = refreshListViewFriends.getRefreshableView();
        
        titleLayout = (RelativeLayout) findViewById(R.id.friends_sorttitle_back);
		title = (TextView) findViewById(R.id.friends_title);
		
		alphabetButton = (Button) findViewById(R.id.alphabetButton);
		sectionToastLayout = (RelativeLayout) findViewById(R.id.section_toast_layout);
		sectionToastText = (TextView) findViewById(R.id.section_toast_text);
		
		btnSure = (Button)findViewById(R.id.myfriends_btn_sure);		
	}

	@Override
	protected void initData() {
		// TODO Auto-generated method stub
//		hideSoftInput();
		Intent intent = this.getIntent();
		userId = intent.getStringExtra("userId");
		groupId = intent.getStringExtra("groupId");
		if(groupId == null){
			groupId = "";
		}
		isCanDouble = intent.getBooleanExtra(strCanDouble, true);
		flag = intent.getIntExtra("flag", 0);
		Object obj = intent.getSerializableExtra("selectedList");
		if(obj != null){
			mSelectedFriends = (ArrayList<PlayerInfo>) obj;
		}
		
//		isCanDouble = false;
//		List<FocusInfo> infos = new ArrayList<FocusInfo>();
//		adapter = new FriendsListAdapter(this, infos);
//		listView.setAdapter(adapter);
		if(flag == 0){
			Logger.i(TAG, "flag=="+flag);
			((TextView)findViewById(R.id.head_myfriends_title)).setText(R.string.myfriends_title_quanzi);
			((TextView)findViewById(R.id.friends_myfriends_title)).setText(R.string.myfriends_title_quanzi);
    	}else if(flag == 1){
    		Logger.i(TAG, "flag11111=="+flag);
    		((TextView)findViewById(R.id.head_myfriends_title)).setText(R.string.myfriends_title_add_friend);
    		((TextView)findViewById(R.id.friends_myfriends_title)).setText(R.string.myfriends_title_add_friend);
    	}
		if (!Helper.checkConnection(MyFriendsActivity.this)) {
            ToastAlone.showToast(MyFriendsActivity.this,
                    getResources().getString(R.string.net_no), 1);
            return;
        }else{
        	if(flag == 0){
        		new GetDataAsync().execute();
        	}else if(flag == 1){
        		new GetFriendsAsync().execute();
        	}
		}
	}

	@Override
	protected void setListener() {
		// TODO Auto-generated method stub
		btn_title_left.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				onBackPressed();
			}
		});
		
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
					long arg3) {
				// TODO Auto-generated method stub
				
			}
		});
		
		btnSure.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				resultData();
			}			
		});
	}
	
	private void resultData(){
		switch (flag) {
		case 0:
		case 1:
			ArrayList<PlayerInfo> listData = new ArrayList<PlayerInfo>();
			if(isCanDouble){//多选
				if(adapter != null && adapter.infos != null){
					for(int i = 0; i < adapter.infos.size();i++){
						if(adapter.infos.get(i).getIsSelected() == 1){
							listData.add(adapter.infos.get(i));
						}
					}					
				}
//				if(listData != null){
					setResult(RESULT_OK, new Intent().putExtra("listdata", listData));
//				}
			}else{//单选
				if(adapter.isSelected){
					if(adapter.infos != null){
						listData.add(adapter.infos.get(adapter.nSelectedPos));
					}					
				}
				setResult(RESULT_OK, new Intent().putExtra("listdata", listData));
			}
			break;

		default:
			break;
		}
		finish();
	}

	@Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        super.onBackPressed();
    }
	
	/**
     * 获取好友
     */
    private class GetDataAsync extends AsyncTask<Void, Void, Boolean> {
        
        private String errorMsg = "";
        
        private ProgressDialog pd;
        private GetUserFriendPageInfo friendPageInfo;
        public GetDataAsync() {                        
           
        }
        
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pd = Utils.getProgressDialog(MyFriendsActivity.this,getResources().getString(R.string.get_data), this);
            pd.show();
        }
        
        @Override
        protected Boolean doInBackground(Void... params) {
            try {
            	friendPageInfo = new NetEngine().getUserFriend(userId,groupId);
            } catch (Exception e) {
                e.printStackTrace();
                errorMsg = e.getMessage();
            }
            return false;
            
        }
//        Uri uri = Uri.parse(versionInfo.url); 
//        Intent it   = new Intent(Intent.ACTION_VIEW,uri); 
//        startActivity(it);
        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            if(pd != null && pd.isShowing()){
                pd.cancel();
            }            
            if (errorMsg.equals("")) {
            	if(friendPageInfo.getCode() == 0){
            		if(friendPageInfo.getObj() != null && friendPageInfo.getObj().size() > 0){
		            	adapter = new FriendsListAdapter(MyFriendsActivity.this, friendPageInfo.getObj(),isCanDouble);
		            	if(listView == null){
		            		return;
		            	}
		        		listView.setAdapter(adapter);
		        		adapter.updataSelect(mSelectedFriends);
		        		setListenerOfListView();
		        		setAlpabetListener();
	        		}
        		}else{        			
        			ToastAlone.showToast(MyFriendsActivity.this, friendPageInfo.getMsg(), 1);
        			if(mSelectedFriends != null && mSelectedFriends.size() > 0){
        				adapter = new FriendsListAdapter(MyFriendsActivity.this, mSelectedFriends,isCanDouble);
		        		listView.setAdapter(adapter);
		        		adapter.updataSelect(mSelectedFriends);
        			}
        		}
            } else {
                ToastAlone.showToast(MyFriendsActivity.this, errorMsg, 1);
            }
        }
    }
    
    /**
     * 获取好友:发面视频时提醒好友用的
     */
    private class GetFriendsAsync extends AsyncTask<Void, Void, Boolean> {
        
        private String errorMsg = "";
        
        private ProgressDialog pd;
        private GetFriendBySharePageInfo friendPageInfo;
        public GetFriendsAsync() {                        
           
        }
        
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pd = Utils.getProgressDialog(MyFriendsActivity.this,getResources().getString(R.string.get_data), this);
            pd.show();
        }
        
        @Override
        protected Boolean doInBackground(Void... params) {
            try {                
            	
            	friendPageInfo = new NetEngine().getFriendsByShareVideo(userId);
            } catch (Exception e) {
                e.printStackTrace();
                errorMsg = e.getMessage();
            }
            return false;
            
        }
//        Uri uri = Uri.parse(versionInfo.url); 
//        Intent it   = new Intent(Intent.ACTION_VIEW,uri); 
//        startActivity(it);
        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            if(pd != null && pd.isShowing()){
                pd.cancel();
            }            
            if (errorMsg.equals("")) {
            	if(friendPageInfo != null){
	            	if(friendPageInfo.getResult().getCode().equals("0")){
	            		if(friendPageInfo.getApp_list() != null && friendPageInfo.getApp_list().size() > 0){
			            	adapter = new FriendsListAdapter(MyFriendsActivity.this, friendPageInfo.getApp_list(),isCanDouble);
			            	adapter.updataSelect(mSelectedFriends);
			        		listView.setAdapter(adapter);
			        		
			        		setListenerOfListView();
			        		setAlpabetListener();
		        		}
	        		}else{        			
	        			ToastAlone.showToast(MyFriendsActivity.this, friendPageInfo.getResult().getMessage(), 1);
	        			if(mSelectedFriends != null && mSelectedFriends.size() > 0){
	        				adapter = new FriendsListAdapter(MyFriendsActivity.this, mSelectedFriends,isCanDouble);
			        		listView.setAdapter(adapter);
			        		adapter.updataSelect(mSelectedFriends);
	        			}
	        		}
            	}else{
            		ToastAlone.showToast(MyFriendsActivity.this, "未知错误", 1);
            	}
            } else {
                ToastAlone.showToast(MyFriendsActivity.this, errorMsg, 1);
            }
        }
    }
    
    class IndexerFriends implements SectionIndexer{

		@Override
		public int getPositionForSection(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public int getSectionForPosition(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public Object[] getSections() {
			// TODO Auto-generated method stub
			return null;
		}
		
		public void setSctions(){
			
		}
    	
    }
    private void hideSoftInput() {    	
        ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
                MyFriendsActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }
    /**
	 * 上次第一个可见元素，用于滚动时记录标识。
	 */
	private int lastFirstVisibleItem = -1;
    /**
	 * 为联系人ListView设置监听事件，根据当前的滑动状态来改变分组的显示位置，从而实现挤压动画的效果。
	 */
	private void setListenerOfListView() {
//		listView.setAdapter(adapter);
		listView.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
					int totalItemCount) {
				// TODO Auto-generated method stub
				int section = adapter.getSectionForPosition(firstVisibleItem);
				int nextSecPosition = adapter.getPositionForSection((section + 1)>=totalItemCount?section:(section+1));
				
				if (firstVisibleItem != lastFirstVisibleItem) {
					MarginLayoutParams params = (MarginLayoutParams) titleLayout.getLayoutParams();
					params.topMargin = 0;
					titleLayout.setLayoutParams(params);
//					title.setText(String.valueOf(alphabet.charAt(section)));
					title.setText(String.valueOf(adapter.sections[section]));
				}
				if (nextSecPosition == firstVisibleItem + 1) {
					View childView = view.getChildAt(0);
					if (childView != null) {
						int titleHeight = titleLayout.getHeight();
						int bottom = childView.getBottom();
						MarginLayoutParams params = (MarginLayoutParams) titleLayout
								.getLayoutParams();
						if (bottom < titleHeight) {
							float pushedDistance = bottom - titleHeight;
							params.topMargin = (int) pushedDistance;
							titleLayout.setLayoutParams(params);
						} else {
							if (params.topMargin != 0) {
								params.topMargin = 0;
								titleLayout.setLayoutParams(params);
							}
						}
					}
				}
				lastFirstVisibleItem = firstVisibleItem;
			}
		});	
	}
	
	/**
	 * 设置字母表上的触摸事件，根据当前触摸的位置结合字母表的高度，计算出当前触摸在哪个字母上。
	 * 当手指按在字母表上时，展示弹出式分组。手指离开字母表时，将弹出式分组隐藏。
	 */
	private void setAlpabetListener() {
		alphabetButton.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				float alphabetHeight = alphabetButton.getHeight();
				float y = event.getY();
				int sectionPosition = (int) ((y / alphabetHeight) / (1f / 27f));
				if (sectionPosition < 0) {
					sectionPosition = 0;
				} else if (sectionPosition > 26) {
					sectionPosition = 26;
				}
				String sectionLetter = String.valueOf(alphabet.charAt(sectionPosition));
//				int position = indexer.getPositionForSection(sectionPosition);
				int position = -1;
				if(sectionPosition < adapter.sections.length){
					position = adapter.getPositionForSection(sectionPosition);
				}
				
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					alphabetButton.setBackgroundResource(R.drawable.a_z_click);
					sectionToastLayout.setVisibility(View.VISIBLE);
					sectionToastText.setText(sectionLetter);
					if(position != -1){
						listView.setSelection(position);
					}
					break;
				case MotionEvent.ACTION_MOVE:
					sectionToastText.setText(sectionLetter);
					if(position != -1){
						listView.setSelection(position);
					}
					break;
				default:
					alphabetButton.setBackgroundResource(R.drawable.a_z);
					sectionToastLayout.setVisibility(View.GONE);
				}
				return true;
			}
		});
	}
    
    /**
	 * 获取sort key的首个字符，如果是英文字母就直接返回，否则返回#。
	 * 
	 * @param sortKeyString
	 *            数据库中读取出的sort key
	 * @return 英文字母或者#
	 */
	private String getSortKey(String sortKeyString) {
//		alphabetButton.getHeight();
		String key = sortKeyString.substring(0, 1).toUpperCase();
		if (key.matches("[A-Z]")) {
			return key;
		}
		return "#";
	}
}
